package hanxx.security.service.impl;

import hanxx.menu.service.MenuService;
import hanxx.security.dao.SysUserDao;
import hanxx.security.domain.SysUser;
import hanxx.security.domain.SysUserLogin;
import hanxx.security.service.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import hanxx.common.utils.uuid.UUID;

import java.util.*;

/**
 * edit:韩鑫鑫
 * 部门:产品研发三部
 **/
@Service
public class SysUserLoginServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private MenuService menuService;
    @Autowired
    private SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUserByUserName = sysUserDao.getSysUserByUserName(username);

        if (Objects.isNull(sysUserByUserName)){
            throw new RuntimeException("用户名不存在1!");
        }
        String token = UUID.fastUUID().toString();
        //  权限
        Set<String> permissions = getPermissions(sysUserByUserName);

        Set<String> rolePermission = roleService.getRolePermission(sysUserByUserName);
        /*List<String> permissions = new ArrayList<>();
        permissions.add("good1");
        permissions.add("test");*/
        return new SysUserLogin(sysUserByUserName,permissions,rolePermission,token);
    }

    private Set<String> getPermissions(SysUser user){
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            perms = menuService.selectMenuPermsByUserId(user.getUserId());
        }
        return perms;
    }
}
